package wxpay

import (
	"bytes"
	"encoding/xml"
	"io/ioutil"
	"net/http"
	"strings"

	uuid "github.com/satori/go.uuid"
)

type DownloadFundFlowReq struct {
	AppId       string `xml:"appid"`
	MchId       string `xml:"mch_id"`
	NonceStr    string `xml:"nonce_str"`
	Sign        string `xml:"sign"`
	BillDate    string `xml:"bill_date"`
	AccountType string `xml:"account_type"`
}

func WxDownloadFundFlow(appId string, billDate string, accountType string) (WxPayResponse, error) {
	var downloadFundFlowReq DownloadFundFlowReq
	downloadFundFlowReq.AppId = appId
	downloadFundFlowReq.MchId = MchId
	sourceUuid := uuid.NewV4()
	formatUuid := strings.Replace(sourceUuid.String(), "-", "", -1)
	downloadFundFlowReq.NonceStr = formatUuid
	downloadFundFlowReq.BillDate = billDate
	downloadFundFlowReq.AccountType = accountType

	var mReqMap map[string]interface{}
	mReqMap = make(map[string]interface{}, 0)
	mReqMap["appid"] = downloadFundFlowReq.AppId
	mReqMap["mch_id"] = downloadFundFlowReq.MchId
	mReqMap["nonceStr"] = downloadFundFlowReq.NonceStr
	mReqMap["bill_date"] = downloadFundFlowReq.BillDate
	mReqMap["account_type"] = downloadFundFlowReq.AccountType
	downloadFundFlowReq.Sign = WxPayCalcSign(mReqMap, MchSecret)

	xmlReq, err := xml.Marshal(downloadFundFlowReq)
	if err != nil {
		return WxPayResponse{}, err
	}
	strReq := string(xmlReq)
	strReq = strings.Replace(strReq, "downloadFundFlowReq", "xml", -1)
	xmlReq = []byte(strReq)

	request, err := http.NewRequest("POST", "https://api.mch.weixin.qq.com/pay/downloadfundflow", bytes.NewReader(xmlReq))
	if err != nil {
		return WxPayResponse{}, err
	}
	request.Header.Set("Accept", "application/xml")
	request.Header.Set("Content-Type", "application/xml;charset=utf-8")

	httpClient := http.Client{}
	response, err := httpClient.Do(request)
	if err != nil {
		return WxPayResponse{}, err
	}

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return WxPayResponse{}, err
	}

	var payResponse WxPayResponse
	err = xml.Unmarshal(responseBody, &payResponse)
	if err != nil {
		return WxPayResponse{}, err
	}

	return payResponse, nil
}
